/**
 * Description：首件检验 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：朱楠
 * date: 2024.7.26
 */
const { reactive, ref, unref } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
const { ElMessage, ElCheckbox, ElInput, ElSelect, ElOption } = ElementPlus
import { useCommon } from '../useCommon.js';
import removeDuplicates from '../../../Scripts/utils/removeDuplicates.js';

export function useFirstCheck() {
  const firstCheckDialogVisible = ref(false);//首件检验对话框默认隐藏
  const firstCheckSelectedContainerList = ref([]);//批次表格响应式数据
  const lossInfoList = ref([]);//报废信息表格响应式数据

  // 报废信息表格列配置
  const lossInfoListColumnConfig = reactive({
    childcontainer: false,//流水卡序号
    childContainerShow: false,//批次号
  });

  const {
    lossReasonList,//【报废原因】响应式数据
    getLossReasonByGroupName,
    unqualifiedFeatureList,//【不合格品特征】响应式数据
    getUnqualifiedFeatureList } = useCommon();

  // 表单数据
  const checkObjInfo = reactive({
    mfgOrderName: '',//生产订单
    planQty: '',//计划数
    containertypename: '',//流水卡类型
    productInfo: '',//零件图号及版本
    productDesc: '',//零件描述
    firstCheckBillNo: '',//首件检验单号
    checkResult: '',//检验结论
    selfCheckQualifiedQty: '',//自检合格数
    selfOutOfToleranceQty: '',//自检超差数
    selfLossQty: '',//自检报废数
    acceptanceQty: '',//合格数(检验总数)
    firstCheckContainerNo: '',//首检批次号
    checkNote: '',//检验备注
    lossQty: '',//报废数
    defectQty: '',//超差数
    reworkQty: '',//返修数
    unqualifiedfeaturename: '',//不合格特征
    workflowstepname: '',//当前工序
  });

  // 表单文本框配置信息
  const enableConfig = reactive({
    acceptanceQtyEnable: false,//【合格数】
    firstCheckContainerNoEnable: true,//【首检批次号】
    checkResultEnable: true,//【检验结论】
    firstCheckBillNoEnable: false,//【首件检验单号】
  });

  // 初始化对话框及赋值
  async function initFirstCheckDialogData(currentSelectContainer, selectionRows, userInfo, factoryUserattributeList) {
    firstCheckDialogVisible.value = true;// 打开对话框
    const { containerid, firstchecknum } = selectionRows[0];
    const {
      mfgordername, planqty, containertypename,
      containertype, productdescription, productname, productrevision, workflowstepid, workflowstepname
    } = currentSelectContainer;

    // 将主界面所选【批次信息】和【批次明细】表格信息合并成一个宽表
    let mergeData = [];
    for (const i of selectionRows) {
      mergeData.push({ ...currentSelectContainer, ...i });
    }

    // 1.获取报废原因列表数据
    await getLossReasonByGroupName({ url: '../../../Ashx/FetchCommonHandler.ashx', method: 'getLossReasonByGroupName', lossreasongroupname: '报废原因组' });

    // 2.获取不合格特征列表数据
    await getUnqualifiedFeatureList({ url: '../../../Ashx/FetchCommonHandler.ashx', method: 'getUnqualifiedFeatureList', factoryid: userInfo.value.factoryid });

    // 3.获取报工人数据
    const workerData = await getWorkerInfo(mergeData, userInfo, factoryUserattributeList);

    // 给【流水卡信息】表格赋值
    firstCheckSelectedContainerList.value = mergeData;
    // 给下方表格数据赋值
    for (const i of workerData) {
      i.editLossQty = 0;// 模板列中【报废数】默认为0
      i.editDefectqty = 0;// 模板列中【超差数】默认为0
      i.editReworkQty = 0;// 模板列中【返修数】默认为0
      i.reasonid = '';// 模板列中【报废原因】默认为空
      i.unqualifiedfeatureids = '';// 模板列中【不合格品特征】默认为空
    }

    // 给【报废信息】表格赋值
    lossInfoList.value = workerData;
    // 给报废表格流水卡号列赋值
    for (const i of workerData) {
      i.realcontainername = mergeData.filter(m => m.containerid === i.containerid)[0].containername;
      i.reasonid = '';
      i.checked = true;//默认全选
    }
    // 给自检超差、自检报废、自检合格文本框赋值
    setSelfCheckInfoData(workerData, containertype);

    // 计算【合格数】、【报废数】、【超差数】、【返修数】总数并赋值
    setCheckInfoSumData(firstCheckSelectedContainerList.value);

    enableConfig.checkResultEnable = false;//禁用【检验结论】
    enableConfig.firstCheckContainerNoEnable = false;//禁用【首检批次号】

    checkObjInfo.mfgOrderName = mfgordername;
    checkObjInfo.workflowstepname = workflowstepname;
    checkObjInfo.planQty = planqty;
    checkObjInfo.containertypename = containertypename;
    checkObjInfo.containertype = containertype;
    checkObjInfo.productDesc = productdescription;
    checkObjInfo.productInfo = `${productname}:${productrevision}`;
    checkObjInfo.firstCheckContainerNo = await getFirstCheckContainerNo(containerid, workflowstepid);//获取【首件批次号】并赋值

    // 首件检验
    if (firstchecknum === 1) {
      checkObjInfo.checkResult = "合格";//【检验结论】默认合格
      checkObjInfo.firstCheckBillNo = await getFirstCheckBillNo(userInfo);//获取【首件检验单号】并赋值
      enableConfig.checkResultEnable = true;//取消禁用【检验结论】
      if (containertype === 2) {
        enableConfig.firstCheckContainerNoEnable = true;//取消禁用【首检批次号】
      }
      // 首检检验，【待检数】都显示为1
      for (const m of firstCheckSelectedContainerList.value) {
        m.checkqty = 1;//表格【待检数】列置为1
      }
    }

    if (containertype != 2) {
      lossInfoListColumnConfig.childcontainer = false;//隐藏【流水卡序号】列
      lossInfoListColumnConfig.childContainerShow = true;//显示【批次号】列
      for (const i of workerData) {
        if (containertype === 7) {
          const filterData = mergeData.filter(item => item.containerid === i.containerid);
          if (filterData.length > 0) {
            i.childContainerShow = filterData[0].containername.split('/')[1];//从批次号中截取【批次号】的值
            i.childContainerName = filterData[0].containername;
          }
        }
        if (containertype === 3) {
          i.childContainerShow = i.containername.split('/')[1];//从批次号中截取【批次号】的值
          i.childContainerName = i.containername;
        }
        // 按批次号排序
        workerData.sort((a, b) => a.childContainerShow - b.childContainerShow);
      }
    } else {
      lossInfoListColumnConfig.childcontainer = false;//隐藏【流水卡序号】列
      lossInfoListColumnConfig.childContainerShow = false;//隐藏【批次号】列
    }
  }

  // 获取首件批次号
  async function getFirstCheckContainerNo(containerid, workflowstepid) {
    const { data } = await useFetch({
      url: `../../../Ashx/ContainerCheckVue3PageHandler.ashx?actions=getFirstCheckContainerNo`,
      data: {
        type: 'getFirstCheckContainerNo',
        containerid, workflowstepid
      }
    });
    return data.value;
  }

  // 获取首件检验单号
  async function getFirstCheckBillNo(userInfo) {
    const year = dayjs().get('year');
    const { data } = await useFetch({
      url: `../../../Ashx/ContainerCheckVue3PageHandler.ashx?actions=getFirstCheckBillNo`,
      data: { type: 'getFirstCheckBillNo', factorycode: `${year}首-${userInfo.value.factorycode}` }
    });
    return data.value;
  }

  // 获取报工信息
  async function getWorkerInfo(mergeData, userInfo, factoryUserattributeList) {
    let checkerid = "", workerSelectChecker = '否';
    if (factoryUserattributeList.value.some(i => i.userattributename === '报工选择检验' && i.attributevalue === '是')) {
      checkerid = userInfo.value.employeeid;
      workerSelectChecker = '是';
    }
    const { data } = await useFetch({
      url: `../../../Ashx/ContainerCheckVue3PageHandler.ashx?actions=getWorkerInfo`,
      data: {
        type: 'getWorkerInfo',
        postData: mergeData,
        checkerid,
        workerSelectChecker//报工选择检验
      }
    });
    return data.value;
  }

  // 给自检超差、自检报废、自检合格文本框赋值
  function setSelfCheckInfoData(workerData, containertype) {
    // 构建自检数据数组
    let selfCheckDataInfo = [];
    for (const i of workerData) {
      const { containerstepworkreportid, selfchecklossqty, selfcheckoutoftoleranceqty, selfcheckqualifiedqty, childcontainerid } = i;
      selfCheckDataInfo.push({ containerstepworkreportid, selfchecklossqty, selfcheckoutoftoleranceqty, selfcheckqualifiedqty, childcontainerid });
    }

    // 对自检数据数组进行去重
    const selfCheckUniquData = removeDuplicates(selfCheckDataInfo);

    if (containertype === 3) {
      checkObjInfo.selfCheckQualifiedQty = selfCheckUniquData[0].selfcheckqualifiedqty;//给【自检合格数】文本框赋值
      checkObjInfo.selfOutOfToleranceQty = selfCheckUniquData[0].selfcheckoutoftoleranceqty;//给【自检超差数】文本框赋值
      checkObjInfo.selfLossQty = selfCheckUniquData.reduce((accumulator, currentItem) => accumulator + currentItem.selfchecklossqty, 0);
    } else {
      let [selfcheckqualifiedqtySum, selfcheckoutoftoleranceqtySum, selfchecklossqtySum] = [0, 0, 0];
      for (const i of selfCheckUniquData) {
        const { selfcheckqualifiedqty, selfcheckoutoftoleranceqty, selfchecklossqty } = i;
        selfcheckqualifiedqtySum += selfcheckqualifiedqty;
        selfcheckoutoftoleranceqtySum += selfcheckoutoftoleranceqty;
        selfchecklossqtySum += selfchecklossqty;
      }
      checkObjInfo.selfCheckQualifiedQty = selfcheckqualifiedqtySum;//给【自检合格数】文本框赋值
      checkObjInfo.selfOutOfToleranceQty = selfcheckoutoftoleranceqtySum;//给【自检超差数】文本框赋值
      checkObjInfo.selfLossQty = selfchecklossqtySum;//给【自检报废数】文本框赋值
    }
  }

  // 给【合格数】、【报废数】、【超差数】文本框赋值
  function setCheckInfoSumData(firstCheckSelectedContainerList) {
    const { containertype, wipqty } = firstCheckSelectedContainerList[0];
    let lossQtySum = 0;// 总报废数
    let reportQtySum = 0;// 总报工数
    let outOfToleranceQtySum = 0;// 总超差数
    let reworkQtySum = 0;// 总返修数
    let otherLossQtySum = 0;//其他报废数（含试件废票数、原报废数）
    let checkqtySum = 0;// 总待检数
    for (const i of lossInfoList.value) {
      if (containertype === 3) {
        checkqtySum = parseInt(i.qty);
      } else {
        checkqtySum += parseInt(i.qty);
      }
      lossQtySum += parseInt(i.editLossQty);
      reworkQtySum += parseInt(i.editReworkQty);
      outOfToleranceQtySum += parseInt(i.editDefectqty);

      // 报工数为0为试件报工
      if (i.qty === 0) {
        reportQtySum += wipqty;//按照在制数累加计算
      } else {
        reportQtySum += i.qty;//累加实际报工数
      }
      otherLossQtySum += parseInt(i.lossqty) + parseInt(i.specimenlossqty) + parseInt(i.editLossQty) + parseInt(i.editDefectqty) + parseInt(i.editReworkQty);
    }

    // //页面【合格数】文本框
    if (containertype === 3) {
      checkObjInfo.acceptanceQty = checkqtySum - otherLossQtySum;
    } else {
      checkObjInfo.acceptanceQty = reportQtySum - otherLossQtySum;
    }

    checkObjInfo.defectQty = outOfToleranceQtySum;//页面【超差数】文本框
    checkObjInfo.lossQty = lossQtySum;//页面【超差数】文本框
    checkObjInfo.reworkQty = reworkQtySum;//页面【超差数】文本框

  }

  // 报废信息表格单元格blur
  function handleFirstCheckDialogCellBlur(label, row, containerList) {
    const mapping = [
      { cellname: '报废数', fieldname: 'editLossQty' },
      { cellname: '超差数', fieldname: 'editDefectqty' },
      { cellname: '返修数', fieldname: 'editReworkQty' },
      { cellname: '报废原因', fieldname: 'reasonid' },
      { cellname: '不合格品特征', fieldname: 'unqualifiedfeatureids' },
    ];
    const { fieldname } = mapping.filter(i => i.cellname === label)[0];
    const editLossQty = parseInt(row.editLossQty);//输入的报废数
    const editDefectqty = parseInt(row.editDefectqty);//输入的超差数
    const editReworkQty = parseInt(row.editReworkQty);//输入的返修数

    const reg = /^[1-9]\d*$/;;//正整数正则
    const { containertype } = containerList[0];
    let qty = containertype === 2 ? parseInt(row.qty) : 1;//报工数，单件单卡和子序号批报工数都为1

    if (label === '报废原因') {
      if (!row.reasonid) {
        row.editLossQty = 0;
        setCheckInfoSumData(containerList);
        return;
      }
      if (editLossQty === 0) {
        row.reasonid = "";
        return ElMessage({ type: 'error', message: `请先填写报废数`, grouping: true });
      }
      setCheckInfoSumData(containerList);
      return;
    }

    if (label === '不合格品特征') {
      if (!row.unqualifiedfeatureids) {
        row.editReworkQty = 0;// 清空返修数
        setCheckInfoSumData(containerList);
        return;
      }
      if (editReworkQty === 0) {
        row.unqualifiedfeatureids = '';//清空【不合格品特征】
        return ElMessage({ type: 'error', message: `请先填写返修数`, grouping: true });
      }
      setCheckInfoSumData(containerList);
      return;
    }

    // 先判断文本框是否为有效数字
    if (!reg.test(row[fieldname])) {
      row[fieldname] = 0;
      if (label === '报废数') {
        row.reasonid = "";//清空【报废原因】
      }
      setCheckInfoSumData(containerList);
      return;
    }

    // 校验报废数 + 返修数 + 超差数是否大于报工数
    // console.log(editLossQty, editDefectqty, editReworkQty, qty)
    if (editLossQty + editDefectqty + editReworkQty > qty) {
      row[fieldname] = 0;
      if (label === '报废数') {
        row.reasonid = "";//清空【报废原因】
      }
      setCheckInfoSumData(containerList);
      return ElMessage({ type: 'error', message: `报废数 + 返修数 + 超差数不能大于${qty}`, grouping: true });
    }
    setCheckInfoSumData(containerList);
  }

  // 检验前数据校验
  function validateCheckData() {
    const selection = lossInfoList.value.filter(row => row.checked);
    if (selection.length === 0) {
      ElMessage({ type: 'error', message: `请选择数据`, grouping: true });
      return false;
    }
    if (selection.some(i => parseInt(i.editLossQty) > 0 && !i.reasonid)) {
      ElMessage({ type: 'error', message: `报废数不为0，请选择【报废原因】`, grouping: true });
      return false;
    }
    if (selection.some(i => parseInt(i.editReworkQty) > 0 && i.unqualifiedfeatureids == '')) {
      ElMessage({ type: 'error', message: `返修数不为0，请至少选择一项【不合格品特征】`, grouping: true });
      return false;
    }
    return true;
  }

  // 保存首件检验数据
  async function saveFirstCheckData(userInfo) {
    if (!validateCheckData()) { return; }
    const selection = lossInfoList.value.filter(row => row.checked);
    const { checkNote, firstCheckContainerNo, firstCheckBillNo } = checkObjInfo;
    console.log({
      type: 'SaveCheckInfo',
      firstCheckSelectedContainerList: firstCheckSelectedContainerList.value,
      postData: selection,//所选择的报废表格
      employeename: userInfo.value.employeename,//检验人
      checkNote, //检验备注
      firstCheckContainerNo,//首检批次号
      firstCheckBillNo,//首件检验单号
    });
    const { data } = await useFetch({
      url: `../../../Ashx/ContainerCheckVue3PageHandler.ashx?actions=SaveCheckInfo`,
      data: {
        type: 'SaveCheckInfo',
        firstCheckSelectedContainerList: firstCheckSelectedContainerList.value,
        postData: selection,//所选择的报废表格
        employeename: userInfo.value.employeename,//检验人
        checkNote, //检验备注
        firstCheckContainerNo,//首检批次号
        firstCheckBillNo,//首件检验单号
      }
    });
    return data;
  }

  // 选择框单元格组件
  const SelectionCell = (props) => {
    return Vue.h(ElCheckbox, {
      modelValue: props.value,
      indeterminate: props.intermediate || false,
      onChange: props.onChange
    })
  };

  // 定义列配置
  const columns = ref([
    {
      key: 'selection',
      width: 50,
      // 行选择框渲染
      cellRenderer: ({ rowData }) => {
        const handleChange = (checked) => { rowData.checked = checked }
        return Vue.h(SelectionCell, { value: rowData.checked, onChange: handleChange })
      },
      // 表头全选框渲染
      headerCellRenderer: () => {
        let _data = unref(lossInfoList)
        const handleCheckAll = (checked) => { lossInfoList.value = _data.map(row => ({ ...row, checked })) }
        const allChecked = _data.every(row => row.checked);
        const someChecked = _data.some(row => row.checked);
        const isIntermediate = someChecked && !allChecked;
        return Vue.h(SelectionCell, { value: allChecked, intermediate: isIntermediate, onChange: handleCheckAll })
      }
    },
    // 行号
    { key: 'rowNumber', title: '序号', width: 60, cellRenderer: ({ rowIndex }) => { return Vue.h('div', null, rowIndex + 1); } },
    { key: 'containerid', dataKey: 'containerid', title: '批次id', width: 80, align: 'left', hidden: true },
    { key: 'workerid', dataKey: 'workerid', title: 'workerid', width: 80, align: 'left', hidden: true },
    { key: 'realcontainername', dataKey: 'realcontainername', title: '流水卡号', width: 180, align: 'left' },
    { key: 'fullname', dataKey: 'fullname', title: '报工人', width: 70, align: 'left' },
    { key: 'createdate', dataKey: 'createdate', title: '报工时间', width: 100, align: 'left', cellRenderer: ({ rowData }) => { return rowData.createdate.split('T')[0] } },
    { key: 'qty', dataKey: 'qty', title: '报工数', width: 70, align: 'left' },
    { key: 'childcontainer', dataKey: 'childcontainer', title: '流水卡序号', width: 100, align: 'left', hidden: !lossInfoListColumnConfig.childcontainer },
    { key: 'childContainerShow', dataKey: 'childContainerShow', title: '批次号', width: 100, align: 'left' },
    { key: 'qty2', dataKey: 'qty2', title: '数量2', width: 60, align: 'left' },
    { key: 'uomname', dataKey: 'uomname', title: '单位', width: 60, align: 'left' },
    { key: 'specimenqty', dataKey: 'specimenqty', title: '试件数', width: 60, align: 'left' },
    { key: 'specimenlossqty', dataKey: 'specimenlossqty', title: '废票试件', width: 60, align: 'left' },
    {
      key: 'editDefectqty', dataKey: 'editDefectqty', title: '超差数', width: 100, align: 'left',
      cellRenderer: ({ rowData }) => {
        return Vue.h(ElInput, {
          modelValue: rowData.editDefectqty,
          'onUpdate:modelValue': (value) => {
            rowData.editDefectqty = value.trim();
          },
          onBlur: () => {
            handleFirstCheckDialogCellBlur('超差数', rowData, firstCheckSelectedContainerList.value)
          }
        });
      }
    },
    {
      key: 'editLossQty', dataKey: 'editLossQty', title: '报废数', width: 100, align: 'left',
      cellRenderer: ({ rowData }) => {
        return Vue.h(ElInput, {
          modelValue: rowData.editLossQty,
          'onUpdate:modelValue': (value) => {
            rowData.editLossQty = value.trim();
          },
          class: 'custom-input-red',
          placeholder: '请输入',
          prefixIcon: 'circle-close-filled',
          onBlur: () => {
            handleFirstCheckDialogCellBlur('报废数', rowData, firstCheckSelectedContainerList.value)
          }
        });
      }
    },
    {
      key: 'reasonid', dataKey: 'reasonid', title: '报废原因', width: 160, align: 'left',
      cellRenderer: ({ rowData }) => {
        // 处理下拉框选择事件
        const handleChange = (value) => {
          rowData.reasonid = value; // 更新当前行数据
        };

        // 构建下拉框选项（ElOption）
        const options = lossReasonList.value.map(option =>
          Vue.h(ElOption, { label: option.lossreasonname, value: option.lossreasonid })
        );

        // 构建下拉框（ElSelect）并嵌套选项
        return Vue.h(ElSelect, {
          modelValue: rowData.reasonid,
          'onUpdate:modelValue': handleChange,
          placeholder: '请选择状态',
          clearable: true,
          onBlur: () => {
            handleFirstCheckDialogCellBlur('报废原因', rowData, firstCheckSelectedContainerList.value)
          }
        },
          options // 子节点：下拉选项列表
        );
      },
    },
    {
      key: 'editReworkQty', dataKey: 'editReworkQty', title: '返修数', width: 100, align: 'left',
      cellRenderer: ({ rowData }) => {
        return Vue.h(ElInput, {
          modelValue: rowData.editReworkQty,
          'onUpdate:modelValue': (value) => {
            rowData.editReworkQty = value.trim();
          },
          class: 'custom-input-red',
          placeholder: '请输入',
          prefixIcon: 'circle-close-filled',
          onBlur: () => {
            handleFirstCheckDialogCellBlur('返修数', rowData, firstCheckSelectedContainerList.value)
          }
        });
      }
    },
    {
      key: 'unqualifiedfeatureids', dataKey: 'unqualifiedfeatureids', title: '不合格品特征', width: 160, align: 'left',
      cellRenderer: ({ rowData }) => {
        // 处理下拉框选择事件
        const handleChange = (value) => {
          rowData.unqualifiedfeatureids = value; // 更新当前行数据
        };

        // 构建下拉框选项（ElOption）
        const options = unqualifiedFeatureList.value.map(option =>
          Vue.h(ElOption, { label: option.unqualifiedfeaturename, value: option.unqualifiedfeatureid })
        );

        // 构建下拉框（ElSelect）并嵌套选项
        return Vue.h(ElSelect, {
          modelValue: rowData.unqualifiedfeatureids,
          'onUpdate:modelValue': handleChange,
          placeholder: '请选择状态',
          clearable: true,
          onBlur: () => {
            handleFirstCheckDialogCellBlur('不合格品特征', rowData, firstCheckSelectedContainerList.value)
          }
        },
          options // 子节点：下拉选项列表
        );
      },
    },
    { key: 'selfcheckqualifiedqty', dataKey: 'selfcheckqualifiedqty', title: '自检合格', width: 60, align: 'left' },
    { key: 'selfcheckoutoftoleranceqty', dataKey: 'selfcheckoutoftoleranceqty', title: '自检超差', width: 60, align: 'left' },
    { key: 'selfchecklossqty', dataKey: 'selfchecklossqty', title: '自检报废', width: 60, align: 'left' },
    { key: 'qty', dataKey: 'qty', title: '原始报工数', width: 60, align: 'left', hidden: true },
    { key: 'containerstepworkreportid', dataKey: 'containerstepworkreportid', title: '报工ID', width: 60, align: 'left', hidden: true },
    { key: 'checktype', dataKey: 'checktype', title: '报工类型', width: 60, align: 'left', hidden: true }
  ]);

  return {
    firstCheckDialogVisible,
    lossInfoList,//报废信息表格响应式数据
    checkObjInfo,//表单数据
    enableConfig,//表单文本框配置信息
    initFirstCheckDialogData,//初始化对话框及赋值
    saveFirstCheckData,
    columns
  };
}